import { createVNode, createApp } from 'vue'

const createContainer = () => {
  const container = document.createElement('div')
  document.body.appendChild(container)
  return container
}

export const useModal = async ({ component, props }) => {
  if (component.__asyncLoader) {
    component = await component.__asyncLoader()
  }

  const instance = createApp({
    render() {
      return createVNode(component, {
        ...props,
        onClosed: () => {
          instance.unmount()
          document.body.removeChild(instance._container)
        }
      })
    }
  })

  const container = createContainer()
  instance.mount(container)
  return instance
}
